import React, { useEffect, useRef, useState } from 'react';
import * as klinecharts from 'klinecharts';
import { init } from 'klinecharts';

interface TimeSharingData {
  timestamp: number;
  price: number;
  volume: number;
  avgPrice?: number;
  preClose: number;
}

interface Props {
  data: TimeSharingData[];
  height?: number;
  showAvgLine?: boolean;
  showVolume?: boolean;
}

const TimeSharingChart: React.FC<Props> = ({ 
  data, 
  height = 500,
  showAvgLine = true,
  showVolume = true
}) => {
  const chartRef = useRef<HTMLDivElement>(null);
  const chartInstanceRef = useRef<any>(null);
  const [currentPrice, setCurrentPrice] = useState<number>(0);
  const [changePercent, setChangePercent] = useState<number>(0);

  useEffect(() => {
    if (!chartRef.current || data.length === 0) return;

    // 使用 init 函数创建图表实例
    chartInstanceRef.current = init(chartRef.current, {
      styles: {
        grid: {
          horizontal: {
            color: '#EDEDED',
            size: 1
          },
          vertical: {
            color: '#EDEDED',
            size: 1
          }
        },
        candle: {
          type: 'area', // 分时图使用线图
          line: {
            size: 1,
            color: '#1677FF'
          },
          area: {
            show: true, // 显示面积图
            lineColor: '#1677FF',
            fillColor: 'rgba(22, 119, 255, 0.1)'
          },
          priceMark: {
            show: true,
            high: {
              show: false
            },
            low: {
              show: false
            }
          },
          tooltip: {
            showRule: 'always',
            showType: 'standard',
            labels: ['时间', '开盘', '收盘', '涨跌幅', '成交量'],
            values: (kLineData: any) => {
              const change = ((kLineData.close - data[0].preClose) / data[0].preClose * 100);
              return [
                { value: kLineData.timestamp, format: 'MM-DD HH:mm' },
                { value: kLineData.open },
                { value: kLineData.close },
                { value: change, format: '.2%' },
                { value: kLineData.volume }
              ];
            }
          }
        },
        technicalIndicator: {
          tooltip: {
            showRule: 'always'
          }
        }
      },
      crosshair: {
        show: true,
        horizontal: {
          line: {
            show: true,
            style: 'dashed'
          },
          text: {
            show: true
          }
        },
        vertical: {
          line: {
            show: true,
            style: 'dashed'
          },
          text: {
            show: true
          }
        }
      },
      yAxis: {
        type: 'percentage'
      }
    });

    // 处理分时数据为K线格式
    const processTimeSharingData = () => {
      const preClose = data[0].preClose;
      console.log('preClose:',preClose)
      const preData = data.map((item, index) => {
        // 对于分时图，open 通常是前一个时间点的 close
        const open = index === 0 ? preClose : data[index - 1].price;
        
        return {
          timestamp: item.timestamp,
          open: open,
          close: item.price,
          high: Math.max(open, item.price),
          low: Math.min(open, item.price),
          volume: item.volume
        };
      });
      console.log('preData:',preData)
      return preData;
    };

    const klineData = processTimeSharingData();
    
    // 设置价格精度
    chartInstanceRef.current.setPriceVolumePrecision(2, 0);
    
    // 应用数据
    chartInstanceRef.current.applyNewData(klineData);

    // 注册自定义技术指标（均价线）
    if (showAvgLine) {
      klinecharts.registerIndicator({
        name: 'AVG_PRICE',
        shortName: 'AVG',
        series: 'price',
        precision: 2,
        shouldOhlc: false,
        calc: (kLineDataList: any[]) => {
          const result: any[] = [];
          let totalAmount = 0;
          let totalVolume = 0;

          kLineDataList.forEach((data, index) => {
            const price = data.close;
            const volume = data.volume || 0;
            
            totalAmount += price * volume;
            totalVolume += volume;
            
            if (totalVolume > 0) {
              result.push({ avg: totalAmount / totalVolume });
            } else {
              result.push({ avg: price });
            }
          });

          return result;
        },
        render: (
          ctx: CanvasRenderingContext2D,
          visibleDataList: any[],
          indicator: any,
          viewport: any,
          xAxis: any,
          yAxis: any
        ) => {
          const dataList = indicator.result;
          ctx.lineWidth = 1;
          ctx.strokeStyle = '#FF9600';
          ctx.beginPath();
          
          visibleDataList.forEach((data, index) => {
            const avgData = dataList[index];
            if (avgData && avgData.avg !== undefined && !isNaN(avgData.avg)) {
              const x = xAxis.convertToPixel(data.timestamp);
              const y = yAxis.convertToPixel(avgData.avg);
              
              if (index === 0) {
                ctx.moveTo(x, y);
              } else {
                ctx.lineTo(x, y);
              }
            }
          });
          
          ctx.stroke();
        }
      });

      // 创建均价线指标
      chartInstanceRef.current.createIndicator('MAVG', false, {
        id: 'candle_pane'
      });
    }

    // 添加成交量
    if (showVolume) {
      chartInstanceRef.current.createIndicator('VOL', true, {
        height: 0.3
      });
    }

    // 更新当前价格
    if (data.length > 0) {
      const latest = data[data.length - 1];
      setCurrentPrice(latest.price);
      setChangePercent(((latest.price - data[0].preClose) / data[0].preClose) * 100);
    }

    // 订阅事件
    // chartInstanceRef.current.createIndicator('crosshair', (crosshair: any) => {
    //   if (crosshair.dataIndex !== undefined && data[crosshair.dataIndex]) {
    //     const hoverData = data[crosshair.dataIndex];
    //     setCurrentPrice(hoverData.price);
    //     setChangePercent(((hoverData.price - data[0].preClose) / data[0].preClose) * 100);
    //   }
    // });

    return () => {
      if (chartInstanceRef.current) {
        klinecharts.dispose(chartRef.current!);
      }
    };
  }, [data, showAvgLine, showVolume]);

  return (
    <div style={{ padding: '16px', background: '#FFFFFF' }}>
      {/* 价格头部信息 */}
      <div style={{ 
        display: 'flex', 
        justifyContent: 'space-between', 
        alignItems: 'center',
        marginBottom: '16px',
        padding: '0 16px'
      }}>
        <div>
          <div style={{ 
            fontSize: '24px', 
            fontWeight: 'bold', 
            color: changePercent >= 0 ? '#EF5350' : '#26A69A' 
          }}>
            {currentPrice.toFixed(2)}
          </div>
          <div style={{ 
            color: changePercent >= 0 ? '#EF5350' : '#26A69A', 
            fontSize: '14px' 
          }}>
            {changePercent >= 0 ? '+' : ''}{changePercent.toFixed(2)}%
          </div>
        </div>
        <div style={{ fontSize: '14px', color: '#666' }}>
          前收: {data[0]?.preClose.toFixed(2)}
        </div>
      </div>

      {/* 图表容器 */}
      <div 
        ref={chartRef} 
        style={{ 
          width: '100%', 
          height: `${height}px`,
          border: '1px solid #E0E0E0',
          borderRadius: '4px'
        }} 
      />

      {/* 图例 */}
      <div style={{ 
        display: 'flex', 
        justifyContent: 'center', 
        marginTop: '8px',
        fontSize: '12px',
        color: '#666'
      }}>
        <div style={{ display: 'flex', alignItems: 'center', margin: '0 8px' }}>
          <div style={{ width: '12px', height: '2px', background: '#1677FF', marginRight: '4px' }}></div>
          分时线
        </div>
        {showAvgLine && (
          <div style={{ display: 'flex', alignItems: 'center', margin: '0 8px' }}>
            <div style={{ width: '12px', height: '2px', background: '#FF9600', marginRight: '4px' }}></div>
            均价线
          </div>
        )}
      </div>
    </div>
  );
};


export default TimeSharingChart;